package com.shopping.controller;

import com.shopping.pojo.*;
import com.shopping.pojo.vo.*;
import com.shopping.service.*;
import com.shopping.utils.R;
import com.shopping.utils.TokenUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;

import java.util.List;

@RestController
@Api(tags = "用户控制类")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private ProductService productService;
    @Autowired
    private BusinessService businessService;
    @Autowired
    private ProductSpecService productSpecService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private CollectService collectService;
    @Autowired
    private CartService cartService;
    @Autowired
    private AddressService addressService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private OrderItemService orderItemService;

    @ApiOperation("用户登录接口")
    @PostMapping("api/login")
    public R login(String userName, String password) {
        // 判断用户名密码是否正确
        if (userService.checkUserNameAndPassword(userName, password)) {
            User user = userService.getUserByUserName(userName);
            // 生成token
            String token = TokenUtils.token(userName, "user", user.getUserId());
            LoginInfo userByToken = TokenUtils.getUserByToken(token);
            if (user.getStatus() == 0) {
                return R.ok().message("登录成功").data("user", userByToken).data("token", token);
            } else {
                return R.error().message("您的帐号已被加入黑名单，请联系网站工作人员");
            }
        } else {
            return R.error().message("用户名或密码错误");
        }
    }

    @ApiOperation("用户注册接口")
    @PostMapping("api/register")
    public R register(User user) {
        // 判断用户名是否重复
        if (userService.checkUserName(user.getUserName())) {
            return R.error().message("用户名已被占用");
        } else {
            if (userService.insertUser(user)) {
                return R.ok().message("注册成功");
            } else {
                return R.error().message("注册失败");
            }
        }
    }

    @ApiOperation("用户忘记密码接口")
    @PostMapping("api/forget")
    public R forget(String userName, String phone, String password) {
        // 验证用户信息
        if (userService.checkUserNameAndPhone(userName, phone)) {
            // 修改密码
            if (userService.updatePassword(userName, password)) {
                return R.ok().message("修改密码成功");
            } else {
                return R.error().message("修改密码失败");
            }
        } else {
            return R.error().message("用户名联系方式匹配错误");
        }
    }

    @ApiOperation("首页商品接口")
    @PostMapping("api/selectMainProduct")
    public R selectMainProduct() {
        List<ProductInfo> recommendProductList = productService.selectMainRecommendProduct();
        List<ProductInfo> newProductList = productService.selectMainNewProduct();
        return R.ok().message("获取首页商品列表成功~").data("recommendProductList", recommendProductList).data("newProductList", newProductList);
    }

    @ApiOperation("分类 根据分类查询商品信息接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/selectProductByCateName")
    public R selectProductByCateNameAndProductName(String cateName) {
        List<ProductInfo> productInfoList = productService.selectProductByCateName(cateName);
        return R.ok().message("获取商品列表成功~").data("productInfoList", productInfoList);
    }

    @ApiOperation("分类 获取全部分类接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/selectCategory")
    public R selectCategory() {
        List<String> categoryList = categoryService.selectCategory();
        return R.ok().message("获取商品分类列表成功~").data("categoryList", categoryList);
    }

    @ApiOperation("首页 获取分类接口")
    @PostMapping("api/selectMainCate")
    public R selectMainCate() {
        List<String> cateSkincareList = categoryService.selectCateSkincare();
        List<String> cateMakeupList = categoryService.selectCateMakeup();
        List<String> cateScentAndCleanList = categoryService.selectCateScentAndClean();
        return R.ok().message("获取首页分类列表成功~").data("cateSkincareList", cateSkincareList).data("cateMakeupList", cateMakeupList).data("cateScentAndCleanList", cateScentAndCleanList);
    }

    @ApiOperation("店铺 搜索店铺接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/selectBusinessByBusinessName")
    public R selectBusinessByBusinessName(String businessName) {
        List<BusinessInfo> businessInfoList = businessService.selectBusinessByBusinessName(businessName);
        return R.ok().message("获取店铺列表成功~").data("businessInfoList", businessInfoList);
    }

    @ApiOperation("店铺 进店获取信息接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/selectBusinessInfoByBusinessId")
    public R selectBusinessInfoByBusinessId(String businessId, String productName) {
        List<ProductInfo> productInfoList = productService.selectProductInfoByBusinessIdAndProductName(businessId, productName);
        BusinessInfo businessInfo = businessService.selectBusinessInfo(businessId);
        return R.ok().message("获取店铺信息成功~").data("productInfoList", productInfoList).data("businessInfo", businessInfo);
    }

    @ApiOperation("商品 搜索商品接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/selectProductByProductName")
    public R selectProductByProductName(String productName) {
        List<ProductInfo> productInfoList = productService.selectProductByProductName(productName);
        return R.ok().message("获取商品列表成功~").data("productInfoList", productInfoList);
    }

    @ApiOperation("商品 获取商品详情信息接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/selectProductInfoByProductId")
    public R selectProductInfoByProductId(String userName, Integer productId) {
        ProductInfo productInfo = productService.selectProductInfoByProductId(productId);
        List<ProductSpec> productSpecList = productSpecService.selectProductSpecByProductId(productId);
        List<CommentInfo> commentInfoList = commentService.selectCommentByProductId(productId);
        User user = userService.getUserByUserName(userName);
        boolean isCollect = collectService.isCollect(user.getUserId(), productId);
        return R.ok().message("获取商品详情信息成功~").data("productInfo", productInfo).data("productSpecList", productSpecList).data("commentInfoList", commentInfoList).data("isCollect", isCollect);
    }

    @ApiOperation("用户 获取用户信息接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/selectUserByUserName")
    public R selectUserByUserName(String userName) {
        User user = userService.getUserByUserName(userName);
        return R.ok().message("获取用户信息成功~").data("user", user);
    }

    @ApiOperation("用户 用户修改信息接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/updateUserInfo")
    public R updateUserInfo(User user) {
        User checkUser = userService.getUserByUserId(user.getUserId());
        if (user.getUserName().equals(checkUser.getUserName())) {
            if (userService.updateUser(user)) {
                return R.ok().message("修改用户信息成功");
            } else {
                return R.error().message("修改用户信息失败");
            }
        } else {
            if (userService.checkUserName(user.getUserName())) {
                return R.error().message("用户名重复，修改用户信息失败");
            } else {
                if (userService.updateUser(user)) {
                    return R.ok().message("修改用户信息成功");
                } else {
                    return R.error().message("修改用户信息失败");
                }
            }
        }
    }

    @ApiOperation("上传用户图片接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/onFileChange")
    public R onFileChangeBusiness(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return R.error().message("文件上传失败");
        }
        String fileName = System.currentTimeMillis() + file.getOriginalFilename();
        String filePath = System.getProperty("user.dir") + System.getProperty("file.separator") + "images" + System.getProperty("file.separator") + "userImg";
        File file1 = new File(filePath);
        if (!file1.exists()) {
            file1.mkdir();
        }
        File dest = new File(filePath + System.getProperty("file.separator") + fileName);
        String storeAvatarPath = "/images/userImg/" + fileName;
        try {
            file.transferTo(dest);
            return R.ok().message("上传图片成功").data("userImage", storeAvatarPath);
        } catch (Exception e) {
            return R.error().message("上传图片失败");
        }
    }

    @ApiOperation("用户 用户修改头像接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/updateUserImage")
    public R onFileChange(String userName, String userImage) {
        if (userService.updateUserImage(userName, userImage)) {
            return R.ok().message("修改头像成功");
        } else {
            return R.error().message("修改头像失败");
        }
    }

    @ApiOperation("收藏 获取用户收藏列表接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/selectCollectByUserName")
    public R selectCollectByUserName(String userName, String productName) {
        List<ProductCollectInfo> productInfoList = collectService.selectCollectProductByUserNameAndProductName(userName, productName);
        return R.ok().message("获取收藏列表成功~").data("productInfoList", productInfoList);
    }

    @ApiOperation("收藏 收藏商品接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/insertCollect")
    public R insertCollect(String userName, Integer productId) {
        User user = userService.getUserByUserName(userName);
        if (collectService.insertCollect(user.getUserId(), productId)) {
            return R.ok().message("收藏商品成功");
        } else {
            return R.error().message("收藏商品失败");
        }
    }

    @ApiOperation("收藏 取消收藏接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/deleteCollect")
    public R deleteCollect(Integer id) {
        if (collectService.deleteCollect(id)) {
            return R.ok().message("取消收藏成功");
        } else {
            return R.error().message("取消收藏失败");
        }
    }

    @ApiOperation("地址 新增地址接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/insertAddress")
    public R insertAddress(String userName, Address address) {
        User user = userService.getUserByUserName(userName);
        address.setUserId(user.getUserId());
        if (addressService.insertAddress(address)) {
            return R.ok().message("新增地址成功");
        } else {
            return R.error().message("新增地址失败");
        }
    }

    @ApiOperation("地址 修改地址接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/updateAddress")
    public R updateAddress(Address address) {
        if (addressService.updateAddress(address)) {
            return R.ok().message("修改地址成功");
        } else {
            return R.error().message("修改地址失败");
        }
    }

    @ApiOperation("地址 删除地址接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/deleteAddress")
    public R deleteAddress(Integer id) {
        if (addressService.deleteAddress(id)) {
            return R.ok().message("删除地址成功");
        } else {
            return R.error().message("删除地址失败");
        }
    }

    @ApiOperation("地址 获取用户地址列表接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/selectAddressByUserId")
    public R selectAddressByUserId(String userName) {
        User user = userService.getUserByUserName(userName);
        List<Address> addressList = addressService.selectAddressByUserId(user.getUserId());
        return R.ok().message("获取地址列表成功~").data("addressList", addressList);
    }

    @ApiOperation("购物车 加入购物车接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/insertCart")
    public R insertCart(String userName, Cart cart) {
        User user = userService.getUserByUserName(userName);
        cart.setUserId(user.getUserId());
        Cart cart1=cartService.isCart(user.getUserId(), cart.getProductId(),cart.getSpecId());
        if (cart1!=null){
            if (cartService.updateCartNumInc(cart1.getCartId())){
                return R.ok().message("加入购物车成功");
            } else {
                return R.error().message("加入购物车失败");
            }
        }else{
            if (cartService.insertCart(cart)) {
                return R.ok().message("加入购物车成功");
            } else {
                return R.error().message("加入购物车失败");
            }
        }
    }

    @ApiOperation("购物车 商品数量加1接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/updateCartNumInc")
    public R updateCartNumInc(Integer cartId) {
        if (cartService.updateCartNumInc(cartId)) {
            return R.ok().message("数量加1成功");
        } else {
            return R.error().message("数量加1失败");
        }
    }

    @ApiOperation("购物车 商品数量减1接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/updateCartNumDec")
    public R updateCartNumDec(Integer cartId) {
        if (cartService.updateCartNumDec(cartId)) {
            return R.ok().message("数量减1成功");
        } else {
            return R.error().message("数量减1失败");
        }
    }

    @ApiOperation("购物车 删除购物车商品接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/deleteCart")
    public R deleteCart(Integer cartId) {
        if (cartService.deleteCart(cartId)) {
            return R.ok().message("删除购物车商品成功");
        } else {
            return R.error().message("删除购物车商品失败");
        }
    }

    @ApiOperation("购物车 获取用户购物车列表接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/selectCartByUserId")
    public R selectCartByUserId(String userName, String productName) {
        User user = userService.getUserByUserName(userName);
        List<ProductCartInfo> productInfoList = cartService.selectCartByUserId(user.getUserId(), productName);
        return R.ok().message("获取用户购物车列表成功~").data("productInfoList", productInfoList);
    }

    @ApiOperation("评论 获取用户评论列表接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/selectCommentByUserId")
    public R selectCommentByUserId(String userName) {
        User user = userService.getUserByUserName(userName);
        List<ProductCommentInfo> commentInfoList = commentService.selectCommentByUserId(user.getUserId());
        return R.ok().message("获取用户评论列表成功~").data("commentInfoList", commentInfoList);
    }

    @ApiOperation("评论 新增评论接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/insertComment")
    public R insertComment(Comment comment, String userName) {
        User user = userService.getUserByUserName(userName);
        comment.setUserId(user.getUserId());
        if (commentService.insertComment(comment)) {
            return R.ok().message("新增评论成功");
        } else {
            return R.error().message("新增评论失败");
        }
    }

    @ApiOperation("评论 删除评论接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/deleteComment")
    public R deleteComment(Integer commentId) {
        if (commentService.deleteComment(commentId)) {
            return R.ok().message("删除评论成功");
        } else {
            return R.error().message("删除评论失败");
        }
    }

    @ApiOperation("订单 获取用户订单列表接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/selectOrdersByUserId")
    public R selectOrdersByUserId(String userName) {
        User user = userService.getUserByUserName(userName);
        List<OrdersInfo> ordersInfoList = ordersService.selectOrdersByUserId(user.getUserId());
        return R.ok().message("获取用户订单列表成功~").data("ordersInfoList", ordersInfoList);
    }

    @ApiOperation("订单 获取用户订单详情接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/selectOrdersByOrderId")
    public R selectOrdersByOrderId(Integer id) {
        OrdersInfo ordersInfo = ordersService.selectOrdersByOrderId(id);
        return R.ok().message("获取用户订单详情成功~").data("ordersInfo", ordersInfo);
    }

    @ApiOperation("订单 收货接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/updateOrderItemReceipt")
    public R updateOrderItemReceipt(Integer id) {
        if (orderItemService.updateOrderItemReceipt(id)) {
            return R.ok().message("收货成功");
        } else {
            return R.error().message("收货失败");
        }
    }

    // @ApiOperation("订单 新增订单接口")
    // @ApiImplicitParam(paramType = "header", name = "token", required = true)
    // @PostMapping("api/insertOrder")
    // public R insertOrder(String userName,Orders orders,@RequestBody List<OrderItem> orderItemList) {
    //     User user = userService.getUserByUserName(userName);
    //     orders.setUserId(user.getUserId());
    //     String str = "DD" + System.currentTimeMillis() + orders.getUserId() % 10 + orders.getPhone().charAt(orders.getPhone().length() - 1) + (int) (Math.random() * 90 + 10);
    //     orders.setOrderId(str);
    //     if (ordersService.insertOrder(orders)) {
    //         int orderId = ordersService.selectIdByOrderId(str);
    //         for (OrderItem orderItem : orderItemList) {
    //             orderItem.setOrderId(orderId);
    //             if (orderItemService.insertOrderItem(orderItem)) {
    //                 return R.ok().message("新增订单成功");
    //             } else {
    //                 return R.error().message("新增详情失败");
    //             }
    //         }
    //         return R.ok().message("新增订单成功");
    //     } else {
    //         return R.error().message("新增订单失败");
    //     }
    // }
    @ApiOperation("订单 新增订单接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/insertOrder")
    public R insertOrder(String userName,Orders orders) {
        User user = userService.getUserByUserName(userName);
        orders.setUserId(user.getUserId());
        String str = "DD" + System.currentTimeMillis() + orders.getUserId() % 10 + orders.getPhone().charAt(orders.getPhone().length() - 1) + (int) (Math.random() * 90 + 10);
        orders.setOrderId(str);
        if (ordersService.insertOrder(orders)) {
            int orderId = ordersService.selectIdByOrderId(str);
            return R.ok().message("新增订单成功").data("orderId",orderId);
        } else {
            return R.error().message("新增订单失败");
        }
    }

    @ApiOperation("订单 新增订单详情接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/insertOrderItem")
    public R insertOrderItem(OrderItem orderItem) {
        if (orderItemService.insertOrderItem(orderItem)){
            return R.ok().message("新增订单详情成功");
        } else {
            return R.error().message("新增订单详情失败");
        }
    }

}

